﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace FileWatch
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private FileSystemWatcher watcher;

        private void AddMessage(string message)
        {
            Dispatcher.BeginInvoke(new Action(() => { WatchOutput.Items.Insert(0, message); }));
        }



        public MainWindow()
        {
            InitializeComponent();
            watcher = new FileSystemWatcher();
            watcher.Deleted += (s, e) =>
                AddMessage($"File:{e.FullPath} Deleted");
            watcher.Renamed += (s, e) =>
            AddMessage($"File renamed from {e.OldName}to{e.FullPath}");
            watcher.Changed += (s, e) =>
            AddMessage($"File:{e.FullPath}{e.ChangeType.ToString()}");
            watcher.Created += (s,e)=>
            AddMessage($"File:{e.FullPath}create");

        }
        private void BrowseButton_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            if(ofd.ShowDialog(this)==true)
            {
                LocationBox.Text = ofd.FileName;
            }

        }

        private void WatchButton_Click(object sender, RoutedEventArgs e)
        {
            watcher.Path = System.IO.Path.GetDirectoryName(LocationBox.Text);
            watcher.Filter= System.IO.Path.GetFileName(LocationBox.Text);
            watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.Size;
            AddMessage("Watching "+LocationBox.Text);
            watcher.EnableRaisingEvents = true;

        }

        private void LocationBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            WatchButton.IsEnabled = !string.IsNullOrEmpty(LocationBox.Text);
        }
    }
}
